import re
from django.urls import reverse

from django import http
from django.contrib.auth import login

from django.shortcuts import render, redirect

# Create your views here.
#导入：
from QQLoginTool.QQtool import OAuthQQ
from django.conf import settings
from django.views import View
import logging

from django_redis import get_redis_connection

from carts.utils import merge_cart_cookie_to_redis
from oauth.utils import generate_access_token, check_access_token
from users.models import User
from .models import OAuthQQUser

logger=logging.getLogger('django')

from meiduo_mall.utils.response_code import RETCODE

class  QQUserView(View):



    def post(self,request):
        """
        接收参数，创建新的用户
        :param request:
        :return:
        """
        #1.接收参数：mobile，password，sms_code,access_token
        mobile=request.POST.get('mobile')
        password=request.POST.get('password')
        sms_code_client=request.POST.get('sms_code')
        access_token=request.POST.get('access_token')
        #2.校验
        if not all([mobile,password,sms_code_client,access_token]):
            return http.HttpResponseForbidden("缺少必传参数")
        if not re.match(r'^1[3-9]\d{9}$',mobile):
            return http.HttpResponseForbidden("手机号格式有误")

        if not re.match(r'^[a-zA-Z0-9]{8,20}$', password):
            return http.HttpResponseForbidden("密码需要8-20位")
        #获取Redis连接
        redis_conn=get_redis_connection('verify_code')
        sms_code_server=redis_conn.get('sms_code_%s'%mobile)
        if sms_code_server is None:
            return render(request,'oauth_callback.html',{'sms_code_errmsg':'无效的短信验证码'})
        if sms_code_client!=sms_code_server.decode():
            return render(request, 'oauth_callback.html', {'sms_code_errmsg':'输入的短信验证码有误'})

        openid=check_access_token(access_token)
        if openid is None:
            return render(request, 'oauth_callback.html', {'sms_code_errmsg': '无效的openid'})
        #3.User表中增加新的用户（先查再曾）
        try:
           user=User.objects.get(mobile=mobile)
        except User.DoesNotExist:
            #没有创建新的用户
            User.objects.create_user(username=mobile,password=password,mobile=mobile)

        else:
            #有，对比密码
            if not user.check_password(password):
                return render(request, 'oauth_callback.html', {'account_errmsg': '用户名或者密码错误'})
        #4.QQUser表增加用户
        try:
            oauth_user=OAuthQQUser.objects.create(openid=openid,user=user)
        except Exception as e:
            return render(request, 'oauth_callback.html', {'qq_login_errmsg': 'qq登录失败'})
        #5.状态保持
        login(request,user)
        #6.设置cookie
        next=request.GET.get('next','/')
        response=redirect(next)
        response.set_cookie('username',user.username,max_age=3600*24*15)
        # 合并购物车
        response = merge_cart_cookie_to_redis(request, user, response)
        #7.返回(从哪里到哪去)
        return response
    '''用户扫码登录的回调处理'''

    def get(self,request):
        '''Oauth2.0认证
        获取code值，取QQ服务器获取openid，判断表中是否存在openid，
        如果有;直接登录
        '''

        #接收Autorization Code
        code=request.GET.get('code')
        if  not code:
            return http.HttpResponseForbidden('缺少参数code')


       #创建工具类对象
        oauth=OAuthQQ(client_id=settings.QQ_CLIENT_ID,
                      client_secret=settings.QQ_CLIENT_SECRET,
                      redirect_uri=settings.QQ_REDIRECT_URI)
        try:

             #携带code向QQ服务器请求access_token
            access_token=oauth.get_access_token(code)

            #携带access_token向QQ服务器 请求openid
            openid=oauth.get_open_id(access_token)
        except Exception as e:
            #如果上面获取openid出错，则验证失效
            logger.error(e)

        #返回结果
            return http.HttpResponseServerError('OAuth2.0认证失败')

            #5.判断表中是否存在openid
        try:
            oauth_user= OAuthQQUser.objects.get(openid=openid)

        except OAuthQQUser.DoesNotExist:
            #从数据库中没有获取到该用户
            access_token=generate_access_token(openid)
            context={
                'access_token':access_token
            }

            return render(request,'oauth_callback.html',context=context)

        else:
            #从数据库中获取到该用户的
           #6根据OAuthQQUser的对象（也就是oauth_user），获取用户
            qq_user=oauth_user.user
            #7状态保持
            login(request,qq_user)

            #8重定向到首页（cookie设置）
            response=redirect(reverse('contents:index'))
          # response = redirect(reverse('contents:index'))
            response.set_cookie('usesrname',qq_user.username,max_age=3600 * 24 * 15)
            # 合并购物车
            response = merge_cart_cookie_to_redis(request, qq_user, response)
            return response






class QQURLView(View):
    """提供QQ登录页面网址
    https://graph.qq.com/oauth2.0/authorize?
    response_type=code&
    client_id=xxx&
    redirect_uri=xxx&
    state=xxx
    """

    def get(self,request):
        #next表示从哪个页面进入到登录页面，将来登录成功，就自动回到那个页面
        next=request.GET.get('next')

        #获取QQ登录页面网址
        #创建OAuthQQ类的对象
        oauth=OAuthQQ(client_id=settings.QQ_CLIENT_ID,
                        client_secret=settings.QQ_CLIENT_SECRET,
                        redirect_uri=settings.QQ_REDIRECT_URI,
                        state=next)

        #调用对象的获取qq地址方法
        login_url=oauth.get_qq_url()

        #返回登录地址
        return http.JsonResponse({'code':RETCODE.OK,'errmsg':'OK',
                                  'login_url':login_url})